<template>
  <!-- 文件管理 -->
  <p-card :bordered="false">
    <!-- 查询区域 -->
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <p-form layout="inline" @keyup.enter.native="searchQuery">
        <p-row :gutter="24">
          <p-col :xl="8" :lg="7" :md="8" :sm="24">
            <p-form-item label="工单号/条码生成编码">
              <p-input placeholder="工单号/条码生成编码" v-model="queryParam.productionno"></p-input>
            </p-form-item>
          </p-col>
          <p-col :xl="8" :lg="7" :md="8" :sm="24">
            <p-form-item label="标签模板名称">
              <p-input placeholder="标签模板名称" v-model="queryParam.labelTemplateName"></p-input>
            </p-form-item>
          </p-col>
          <p-col :xl="8" :lg="7" :md="8" :sm="24">
            <p-form-item label="领用人">
              <p-input placeholder="领用人" v-model="queryParam.empname"></p-input>
            </p-form-item>
          </p-col>
          <p-col :xl="8" :lg="7" :md="8" :sm="24">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <p-button type="primary" @click="searchQuery" icon="search">查询</p-button>
              <p-button
                type="primary"
                @click="searchReset"
                icon="reload"
                style="margin-left: 8px"
              >重置</p-button>
              <!-- 高级查询区域 -->
              <j-super-query
                style="margin-left: 8px"
                :fieldList="fieldList"
                ref="superQueryModal"
                @handleSuperQuery="handleSuperQuery"
              ></j-super-query>

              <p-button type="primary" @click="handleAlert" style="margin-left: 8px">领用</p-button>
            </span>
          </p-col>
        </p-row>
      </p-form>
    </div>
    <!-- 查询区域-END -->

    <!-- 操作按钮区域 -->
    <div class="table-operator"></div>
    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择
        <a style="font-weight: 600">{{ selectedRowKeys.length }}</a>项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>

        <span style="float:right;">
          <p-divider type="vertical" />
          <a @click="loadData()">
            <p-icon type="sync" />刷新
          </a>
          <p-divider type="vertical" />
          <p-popover title="自定义列" trigger="click" placement="leftBottom" :overlay-style="getWidth">
            <template slot="content">
              <p-checkbox-group
                @change="onColSettingsChange"
                v-model="settingColumns"
                :defaultValue="settingColumns"
              >
                <p-row>
                  <template v-for="(item,index) in defColumns" >
                    <template v-if="item.key!='rowIndex'&& item.dataIndex!='action'">
                      <p-col :span="12" v-bind:key="index">
                        <p-checkbox :value="item.dataIndex" >{{ item.title }}</p-checkbox>
                      </p-col>
                    </template>
                  </template>
                </p-row>
              </p-checkbox-group>
            </template>
            <a>
              <p-icon type="setting" />自定义列
            </a>
          </p-popover>
        </span>
      </div>

      <p-table
        ref="table"
        size="middle"
        bordered
        rowKey="id"
        :columns="columns"
        :scroll="tableScroll"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
        @change="handleTableChange"
      >
        <template slot="htmlSlot" slot-scope="text">
          <div v-html="text"></div>
        </template>
        <template slot="imgSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无此图片</span>
          <img
            v-else
            :src="getImgView(text)"
            height="25px"
            alt="图片不存在"
            style="max-width:80px;font-size: 12px;font-style: italic;"
          />
        </template>
      </p-table>
    </div>

    <getLabel-List ref="modalForm" :EnhanceJS="EnhanceJS" @passVaule="passValue"></getLabel-List>
  </p-card>
</template>

<script>
import { JeecgListMixin } from "@/mixins/JeecgListMixin";
// import { api } from "@/api/manage";
// 高级查询弹窗
import JSuperQuery from "@/components/jeecg/JSuperQuery.vue";
import { filterObj } from "@/utils/util";
// 新增弹窗
import GetLabelList from "./modules/GetLabelList";
import {  queryUserByDepId } from '@/api/api'
import Vue from "vue";
import {
  initDictOptions,
  filterMultiDictText,
} from "@/components/dict/JDictSelectUtil";
import ButtonExpHandler from "@/components/jeecgbiz/modules/ButtonExpHandler";
import { postAction, getAction, deleteAction,putAction } from "@/api/manage";
import FxCompontensModal from "@/components/jeecgbiz/FxCompontensModal";
import { mapState } from 'vuex'
import moment from 'moment';

//高级查询modal需要参数
const superQueryFieldList = [
  {
    value: "fileCode",
    text: "文件编码",
    type: "String",
  },
  {
    value: "fileName",
    text: "文件名称",
    type: "String",
  },
  {
    value: "fileVersion",
    text: "文件版本",
    type: "String",
  },
  {
    value: "fileUrl",
    text: "文件附件",
    type: "String",
  },
  {
    value: "fileType",
    text: "文件类型",
    type: "select",
    dictCode: "quality_file_type",
  },
  {
    value: "createBy",
    text: "创建者",
    type: "String",
  },
  {
    value: "createTime",
    text: "创建时间",
    type: "Date",
  },
  {
    value: "updateBy",
    text: "修改者",
    type: "String",
  },
  {
    value: "updateTime",
    text: "修改时间",
    type: "Date",
  },
  {
    value: "remarks",
    text: "备注",
    type: "String",
  },
  {
    value: "status",
    text: "状态",
    type: "select",
    dictCode: "mes_quailty_file_status",
  },
];

export default {
  name: "MesQcQualityFileManagementList",
  mixins: [JeecgListMixin],
  components: {
    JSuperQuery,
    FxCompontensModal,
    GetLabelList,
  },
  data() {
    return {
      moment,
      fieldList: superQueryFieldList,
      superQueryFlag: false,
      superQueryParams: "",
      description: "文件管理管理页面",
      EnhanceJS: "",
      cgButtonLinkList: [],
      cgButtonList: [],
      title: "", //存表名
      groupTag: [],
      queryInfo: [],
      code: "",
      // 表头
      columns: [],
      //列设置
      settingColumns: [],
      //列定义
      defColumns: [
        {
          title: "序号",
          dataIndex: "",
          key: "rowIndex",
          width: 60,
          align: "center",
          customRender: function (t, r, index) {
            return parseInt(index) + 1;
          },
        },
        {
          title: "工单号/条码生成编码",
          align: "center",
          dataIndex: "productionno",
          customRender: function (t, r, index) {
           if(t){
             return t
           }else{
             return r.barcodeProduceNo
           }
          },
        },
        {
          title: "首标签条码",
          align: "center",
          dataIndex: "beginBarcode",
        },
        {
          title: "尾标签条码",
          align: "center",
          dataIndex: "endBarcode",
        },
        
        {
          title: "标签模板名称",
          align: "center",
          dataIndex: "labelTemplateName",
        },
        {
          title: "条码规则名称",
          align: "center",
          dataIndex: "ruleName",
        },

        {
          title: "数量",
          align: "center",
          dataIndex: "qty",
        },

        // {
        //   title: "打印类型",
        //   align: "center",
        //   dataIndex: "printType",
        //   customRender: function (t, r, index) {
        //     if(t==0){
        //       return "打印"
        //     }
        //   },
        // },

        {
          title: "打印人",
          align: "center",
          dataIndex: "name",
        },

        {
          title: "打印时间",
          align: "center",
          dataIndex: "time",
         customRender: function (text) {
           return moment(text).format("YYYY-MM-DD hh:mm:ss");
          },
        },
       

        {
          title: "领用状态",
          align: "center",
          dataIndex: "status",
           customRender: function (t, r, index) {
            if(t==0){
              return "未领用"
            }else if(t==1){
              return "已领用"
            }
          },
        },
        {
          title: "领用人工号",
          align: "center",
          dataIndex: "empno",
        },
        {
          title: "领用人姓名",
          align: "center",
          dataIndex: "empname",
        },
        {
          title: "领用人联系方式",
          align: "center",
          dataIndex: "linkphone",
        },
        {
          title: "领用人部门",
          align: "center",
          dataIndex: "dptname",
        },
         {
          title: "领用时间",
          align: "center",
          dataIndex: "takeuserDt",
         customRender: function (text) {
           if(text){
             return moment(text).format("YYYY-MM-DD hh:mm:ss");
           }else{
             return ""
           }
          },
        },
        
      ],
      url: {
        list: "/mes-code/mesBcPrint/list",
        delete: "/mes-quality/mesQcQualityFileManagement/delete",
        deleteBatch: "/mes-quality/mesQcQualityFileManagement/deleteBatch",
        exportXlsUrl: "/mes-quality/mesQcQualityFileManagement/exportXls",
        importExcelUrl:
          "/mes-quality/mesQcQualityFileManagement/importExcel",
        getColumns: "/mes-quality/online/cgform/api/getColumns/",
        buttonAction: "/mes-quality/online/cgform/api/doButton",
        uid:'/poros-authcenter/user/message'
      },
      dictOptions: {
        fileType: [],
        status: [],
      },
      /* 分页参数 */
      ipagination: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ["10", "20", "50"],
        showTotal: (total, range) => {
          return range[0] + "-" + range[1] + " 共" + total + "条";
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0,
      },
      selectedMainId: "",
    };
  },
  computed: {
    importExcelUrl: function () {
      return `${api.test}${this.url.importExcelUrl}`;
    },
    getWidth: function () {
      if (this.defColumns.length > 14) {
        return { width: "500px" };
      }
    },
    newSelectedMainId: function () {
      if (typeof this.selectedMainId == "number") {
        return this.selectedMainId.toString();
      } else {
        return this.selectedMainId;
      }
    },
    tableScroll: function () {
      if (this.columns.length > 13) {
        return { x: this.columns.length * 150 - 450 };
      }
    },
    ...mapState({
      userInfo:state => state.user,
    })
  },

  created() {
    this.initButtonList();
    this.initColumns();
    this.setdefColumns();
  },

  methods: {
    getUserList(){
      var params=this.userInfo.uid
      getAction('/poros-permission/secStaff/getUserByUid/'+params).then((res) => {
          if (res.code == 0) {
            this.EnhanceJS.userInfo=res.data
          }
        })
    },
  
    setdefColumns() {
      if (this.columns.length > 13) {
        let arrLength = this.columns.length - 1;
        this.columns.forEach((item, index) => {
          item["width"] = 130;
        });
        this.columns[0]["width"] = "60px";
        this.columns[0]["fixed"] = "left";
        this.columns[1]["fixed"] = "left";
      }
    },
    handleAlert: function () {
      if(this.selectionRows.length>0){
        let isOK=true
        this.selectionRows.forEach(item=>{
          if(item.status==1){
            isOK= false
          }
        })
        if(isOK){

        
       var aData = new Date();
       this.Data=aData.getFullYear() +"-" +(aData.getMonth() + 1) +"-" +aData.getDate()+" "+aData.getHours()+":"+aData.getMinutes()+":"+aData.getSeconds(),
        this.getUserList()  
      this.EnhanceJS={
        userInfo:this.userInfo,
        Data:moment(this.Data,'YYYY-MM-DD'),
        dataSource:this.selectionRows
      },
        this.$refs.modalForm.add();
        this.$refs.modalForm["getRuleCodeValue"]
          ? this.$refs.modalForm.getRuleCodeValue()
          : "";
        this.$refs.modalForm.title = "提示";
        this.$refs.modalForm.disableSubmit = false;
        }else{
          this.$message.error('该工单已领用')
        }
        }else{
          this.$message.error('请选择生产工单')
        }
    },
    initColumns() {
      //权限过滤（列权限控制时打开，修改第二个参数为授权码前缀）
      //this.defColumns = colAuthFilter(this.defColumns,'testdemo:');

      var key = this.$route.name + ":colsettings";
      let colSettings = Vue.ls.get(key);
      if (colSettings == null || colSettings == undefined) {
        let allSettingColumns = [];
        this.defColumns.forEach(function (item, i, array) {
          allSettingColumns.push(item.dataIndex);
        });
        this.settingColumns = allSettingColumns;
        this.columns = this.defColumns;
      } else {
        this.settingColumns = colSettings;
        const cols = this.defColumns.filter((item) => {
          if (item.key == "rowIndex" || item.dataIndex == "action") {
            return true;
          }
          if (colSettings.includes(item.dataIndex)) {
            return true;
          }
          return false;
        });
        this.columns = cols;
      }
    },
    //列设置更改事件
    onColSettingsChange(checkedValues) {
      var key = this.$route.name + ":colsettings";
      Vue.ls.set(key, checkedValues, 7 * 24 * 60 * 60 * 1000);
      this.settingColumns = checkedValues;
      const cols = this.defColumns.filter((item) => {
        if (item.key == "rowIndex" || item.dataIndex == "action") {
          return true;
        }
        if (this.settingColumns.includes(item.dataIndex)) {
          return true;
        }
        return false;
      });
      this.columns = cols;
    },
    //高级查询方法
    handleSuperQuery(arg) {
      if (!arg) {
        this.superQueryParams = "";
        this.superQueryFlag = false;
      } else {
        this.superQueryFlag = true;
        this.superQueryParams = JSON.stringify(arg);
      }
      this.loadData();
    },
    // 获取查询条件
    getQueryParams() {
      var newData={
        limit:this.ipagination.pageSize,
        pageNo:this.ipagination.current,
        productionno:this.queryParam.productionno,
        labelTemplateName:this.queryParam.labelTemplateName,
        empname:this.queryParam.empname
      }
      return filterObj(newData);
    },
    initDictConfig() {
      initDictOptions("quality_file_type").then((res) => {
        if (res.success) {
          this.$set(this.dictOptions, "fileType", res.data);
        }
      });
      initDictOptions("mes_quailty_file_status").then((res) => {
        if (res.success) {
          this.$set(this.dictOptions, "status", res.data);
        }
      });
    },
    clickThenSelect(record) {
      return {
        on: {
          click: () => {
            this.onSelectChange(record.id.split(","), [record]);
          },
        },
      };
    },
    onClearSelected() {
      this.selectedRowKeys = [];
      this.selectionRows = [];
      this.selectedMainId = "";
    },
    onSelectChange(selectedRowKeys, selectionRows) {
      this.selectedMainId = selectedRowKeys[0];
      this.selectedRowKeys = selectedRowKeys;
      this.selectionRows = selectionRows;
    },
    loadData(arg) {
      if (!this.url.list) {
        this.$message.error("请设置url.list属性!");
        return;
      }
      //加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination.current = 1;
      }
      this.onClearSelected();
      var params = this.getQueryParams(); //查询条件
      this.loading = true;
      getAction(this.url.list, params).then((res) => {
        if (res.success) {
          this.dataSource = res.data.records;
          this.ipagination.total = res.data.total;
        }
        if (res.code === 510) {
          this.$message.warning(res.msg);
        }
        this.loading = false;
      });
    },
    

    // 弹出窗组件
    showDemoModal() {
      this.$refs.modalCompon.modalShow();
    },
    // 点击btn获取数据
    btnGetData(tableName, title) {
      getAction(`${this.url.getColumns}`, {
        tableName: tableName,
      }).then((res) => {
        if (res.code == 0) {
          this.queryInfo = res.data.columns;
          this.title = title;
          this.dictOptions = res.data.dictOptions;
          this.showDemoModal();
        } else {
          this.$message.warning(res.msg);
        }
      });
    },

    //筛选分组
    getGroupTag(arrList) {
      let arr = [];
      var map = {},
        dest = [];
      arrList.forEach((item, index) => {
        if (item.groupTag) {
          arr.push(item);
        }
      });
      for (var i = 0; i < arr.length; i++) {
        var ai = arr[i];
        if (!map[ai.groupTag]) {
          dest.push({
            groupTag: ai.groupTag,
            name: ai.groupName,
            data: [ai],
          });
          map[ai.groupTag] = ai;
        } else {
          for (var j = 0; j < dest.length; j++) {
            var dj = dest[j];
            if (dj.groupTag == ai.groupTag) {
              dj.data.push(ai);
              break;
            }
          }
        }
      }
      this.groupTag = dest;
      console.log(dest);
    },
    showLinkButton(item, record) {
      let btn = new ButtonExpHandler(item.exp, record);
      return btn.show;
    },
    initButtonList() {
      
    },
    initCgEnhanceJs(enhanceJs) {
      //console.log("--onlineList-js增强",enhanceJs)
      if (enhanceJs) {
        let Obj = eval("(" + enhanceJs + ")");
        this.EnhanceJS = new Obj(getAction, postAction, deleteAction);
        this.cgButtonJsHandler("created");
      } else {
        this.EnhanceJS = "";
      }
    },
    initCgButtonList(btnList) {
      let linkArr = [];
      let buttonArr = [];
      if (btnList && btnList.length > 0) {
        for (let i = 0; i < btnList.length; i++) {
          let temp = btnList[i];
          if (temp.buttonStyle == "button") {
            buttonArr.push(temp);
          } else if (temp.buttonStyle == "link") {
            linkArr.push(temp);
          }
        }
      }
      this.cgButtonLinkList = [...linkArr];
      this.cgButtonList = [...buttonArr];
      console.log("链接增强", this.cgButtonLinkList);
    },
    cgButtonJsHandler(buttonCode) {
      if (this.EnhanceJS[buttonCode]) {
        this.EnhanceJS[buttonCode](this);
      }
    },
    cgButtonActionHandler(buttonCode) {
      //处理自定义button的 需要配置该button自定义sql
      if (!this.selectedRowKeys || this.selectedRowKeys.length == 0) {
        this.$message.warning("请先选中一条记录");
        return false;
      }
      if (this.selectedRowKeys.length > 1) {
        this.$message.warning("请只选中一条记录");
        return false;
      }
      let params = {
        formId: this.code,
        buttonCode: buttonCode,
        dataId: this.selectedRowKeys[0],
      };
      console.log("自定义按钮请求后台参数：", params);
      postAction(this.url.buttonAction, params).then((res) => {
        if (res.success) {
          this.loadData();
          this.$message.success("处理完成!");
        } else {
          this.$message.warning("处理失败!");
        }
      });
    },
    cgButtonLinkHandler(record, buttonCode, optType) {
      if (optType == "js") {
        if (this.EnhanceJS[buttonCode]) {
          this.EnhanceJS[buttonCode](this, record);
        }
      } else if (optType == "action") {
        let params = {
          formId: this.code,
          buttonCode: buttonCode,
          dataId: record.id,
        };
        postAction(this.url.buttonAction, params).then((res) => {
          if (res.success) {
            this.loadData();
            this.$message.success("处理完成!");
          } else {
            this.$message.warning("处理失败!");
          }
        });
      }
    },
    passValue(){
      this.loadData()
    },
    handleTableChange(a){
      this.ipagination.current=a.current
      this.ipagination.pageSize=a.pageSize
      this.loadData()
    }
  },

  
};
</script>
<style scoped>
@import "~@assets/less/common.less";
</style>
